<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import ip from '@/utils/baseURL.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 获取当前用户的 session
const session = localStorage.getItem('session');

// 新闻列表数据
const newsList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 新闻表单数据
const newsForm = ref({
  id: '',
  title: '',
  mainBody: '',
  label: '',
  time: new Date()
})

// 表单规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  mainBody: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  label: [{ required: true, message: '请选择类型', trigger: 'change' }]
}

// 新闻类型选项
const labelOptions = [
  { label: '新闻动态', value: '新闻动态' },
  { label: '通知公告', value: '通知公告' },
  { label: '成果交流', value: '成果交流' }
]

// 添加表单 ref
const formRef = ref(null)

// 添加 loading 状态
const loading = ref(false)

// 添加排序和筛选状态
const sortOrder = ref('descending') // 默认降序
const selectedType = ref('') // 类型筛选

// 获取新闻列表
const fetchNewsList = async () => {
  try {
    const response = await axios.get(`${ip}/inter/journalism/getJournalism`)
    if (response.data.code === 200) {
      let filteredList = [...response.data.data]
      
      // 类型筛选
      if (selectedType.value) {
        filteredList = filteredList.filter(item => item.label === selectedType.value)
      }
      
      // 时间排序
      filteredList.sort((a, b) => {
        const timeA = a.time ? a.time[0] * 10000 + a.time[1] * 100 + a.time[2] : 0
        const timeB = b.time ? b.time[0] * 10000 + b.time[1] * 100 + b.time[2] : 0
        return sortOrder.value === 'ascending' ? timeA - timeB : timeB - timeA
      })
      
      newsList.value = filteredList
      total.value = filteredList.length
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
  }
}

// 获取新闻详情
const fetchNewsDetail = async (id) => {
  try {
    const response = await axios.get(`${ip}/inter/journalism/getJournalismById`, {
      params: { id }
    })
    if (response.data.code === 200) {
      console.log('后端返回的完整数据:', response.data.data)
      const { title, mainBody, label, time } = response.data.data
      
      // 格式化时间为 YYYY-MM-DD 字符串
      const formatDate = (timeArr) => {
        if (!timeArr || !Array.isArray(timeArr) || timeArr.length < 3) return ''
        const [year, month, day] = timeArr
        const formatNumber = (n) => String(n).padStart(2, '0')
        return `${year}-${formatNumber(month)}-${formatNumber(day)}`
      }

      newsForm.value = {
        id,
        title,
        mainBody,
        label: response.data.data.label || '',
        time: formatDate(time)
      }
    }
  } catch (error) {
    console.error('获取新闻详情失败:', error)
    ElMessage.error('获取新闻详情失败')
  }
}

// 添加/编辑新闻
const handleAddOrEdit = (row) => {
  if (row) {
    isEdit.value = true
    dialogTitle.value = '编辑新闻'
    fetchNewsDetail(row.id)
  } else {
    isEdit.value = false
    dialogTitle.value = '添加新闻'
    // 格式化当前日期为 YYYY-MM-DD
    const today = new Date()
    const formatToday = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
    
    newsForm.value = {
      id: '',
      title: '',
      mainBody: '',
      label: '',
      time: formatToday
    }
  }
  dialogVisible.value = true
}

// 删除新闻
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条新闻吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里需要替换为实际的删除接口
      await axios.delete(`${ip}/inter/adminJournalism/delete?id=${row.id}`,{headers: {
        'Session': `${session}`, // 传递 session
      },
      });
      ElMessage.success('删除成功')
      fetchNewsList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 修改格式化时间函数，只显示到日期
const formatTime = (timeArr) => {
  if (!timeArr || !Array.isArray(timeArr) || timeArr.length < 3) {
    return '-'
  }
  const [year, month, day] = timeArr
  // 补零处理
  const formatNumber = (n) => String(n).padStart(2, '0')
  return `${year}-${formatNumber(month)}-${formatNumber(day)}`
}

// 修改提交表单方法
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        // 将日期字符串转换为数组
        const dateArr = newsForm.value.time.split('-').map(Number)
        
        // 构造提交的数据
        const submitData = {
          title: newsForm.value.title,
          label: newsForm.value.label,
          time: dateArr, // [年, 月, 日]
          mainBody: newsForm.value.mainBody
        }

        // 如果是编辑模式，添加 id
        if (isEdit.value) {
          submitData.id = newsForm.value.id
        }

        await axios.post(`${ip}/inter/adminJournalism/saveOrUpdate`, submitData,{headers: {
          'Session': `${session}`, // 传递 session
        },
        });
        
        ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
        dialogVisible.value = false
        fetchNewsList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 处理排序变化
const handleSortChange = ({ order }) => {
  sortOrder.value = order || 'descending'
  fetchNewsList()
}

// 处理类型筛选变化
const handleTypeChange = (value) => {
  selectedType.value = value
  fetchNewsList()
}

onMounted(() => {
  fetchNewsList()
})
</script>

<template>
  <div class="news-page">
    <div class="header">
      <h2>新闻动态管理</h2>
      <div class="header-right">
        <!-- 添加类型筛选 -->
        <el-select
          v-model="selectedType"
          placeholder="选择新闻类型"
          clearable
          @change="handleTypeChange"
          style="margin-right: 16px; width: 160px;"
        >
          <el-option
            v-for="item in labelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="handleAddOrEdit()">添加新闻</el-button>
      </div>
    </div>

    <!-- 修改新闻列表，添加排序功能 -->
    <el-table 
      :data="newsList" 
      style="width: 100%" 
      v-loading="loading"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="label" label="类型" width="120" />
      <el-table-column 
        label="发布时间" 
        width="180"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
        :sort-by="sortOrder"
      >
        <template #default="{ row }">
          {{ formatTime(row.time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleAddOrEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="newsForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="newsForm.title" />
        </el-form-item>
        <el-form-item label="类型" prop="label">
          <el-select v-model="newsForm.label" placeholder="请选择新闻类型">
            <el-option
              v-for="item in labelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="time">
          <el-date-picker
            v-model="newsForm.time"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="内容" prop="mainBody">
          <el-input
            v-model="newsForm.mainBody"
            type="textarea"
            :rows="10"
            placeholder="请输入新闻内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.news-page {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
    }

    .header-right {
      display: flex;
      align-items: center;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.el-table) {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>